package cn.zzf.algs.note.base.collection.v1;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @author GaoFeng
 * @date 2019/11/19 10:01
 * 使用单向链表实现的栈
 */
public class LinkedListStack<T> implements Iterable<T>, Stack<T> {

    /** 首节点  */
    private Node first;


    /** 栈的总大小 */
    private int size;

    public LinkedListStack() {
        first = null;
        size = 0;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {

            /** 当前节点 */
            private Node currentNode = first;

            @Override
            public boolean hasNext() {
                return currentNode != null;
            }

            @Override
            public T next() {

                if (currentNode != null) {
                    T value = currentNode.value;
                    currentNode = currentNode.next;
                    return value;
                }

                return null;
            }
        };
    }

    @Override
    public void forEach(Consumer<? super T> action) {
    }

    @Override
    public Spliterator<T> spliterator() {
        return null;
    }

    public class Node {

        T value;
        Node next;

        Node() {

        }

        Node(T value) {
            this.value = value;
        }

    }

    @Override
    public void push(T value) {

        if (first == null) {
           // 初始化头和尾
           first = new Node(value);
        } else {
           // 改变尾部节点
            Node node = new Node(value);
            node.next = first;
            first = node;
        }

        size++;
    }


    @Override
    public T pop() {

        if (first == null) {
            return null;
        }

        T value = first.value;
        first = first.next;

        return value;
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return size > 0;
    }

    /**
     *
     * @author ZengZhengFang
     * @date 2019/11/27 9:58
     * @param element 将链表中与之相等的元素删除
     * @return int
     */
    public int remove(T element) {

        Node currentNode = first;
        Node beforeNode = first;

        int removeCount = 0;
        while (currentNode != null) {

            T value = currentNode.value;
            if (element.equals(value)) {
                if (currentNode.next != null) {
                    beforeNode.next = beforeNode.next.next;
                    removeCount++;
                }
            }

            beforeNode = currentNode;
            currentNode = currentNode.next;

        }

        return removeCount;

    }
}